<?php

namespace App\Http\Resources;

use App\Models\System;
use Carbon\Carbon;
use App\Http\Responses\Resource;
use App\Http\Resources\User as UserCollection;
use App\Models\User as User;

class Notification extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        $has_parent = array_key_exists('parent',$this->data);
//        dd($has_parent);
//
//        dd($this->data);
        return [
            'id' => $this->id,
            'type' => snake_case(class_basename($this->type)) ,
            'from' => $this->getFrom(),
            'data' => [
                'title' => $this->data['title'],
                'content' => $this->data['content'],
                'parent' => $this->when($has_parent,!$has_parent?: $this->data['parent'])
            ],
            'read_at' => Carbon::parse($this->read_at)->toDateTimeString(),
            'created_at' => Carbon::parse($this->created_at)->toDateTimeString()

        ];
    }


    private function getFrom(){

        $type = $this->data['from_type'];

        if ($type == 0){

            return System::notifer()->toArray();

        }

        $user_id = $this->data['from_id'];

        $user = User::find($user_id);
        return new UserCollection($user);


    }
}
